/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yanzhenjie.andserver.slice;

import cn.bingoogolapple.refreshlayout.BgaStickinessRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BgarefreshLayout;
import com.github.clans.fab.FloatingActionButton;
import com.lxj.xpopup.XPopup;
import com.yanzhenjie.andserver.MyCommonEventSubscriber;
import com.yanzhenjie.andserver.dialog.CustomAttachPopup2;
import com.yanzhenjie.andserver.dialog.ZhihuCommentPopup;
import com.yanzhenjie.andserver.event.MessageEvent;

import com.yanzhenjie.andserver.model.fileItemModel;
import com.yanzhenjie.andserver.provider.ListProvider;
import com.yanzhenjie.andserver.util.FileUtils;
import com.yanzhenjie.hos.ResourceTable;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.MatchingSkills;
import ohos.multimodalinput.event.TouchEvent;
import ohos.rpc.RemoteException;
import ohos.utils.IntentConstants;
import ohos.utils.net.Uri;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener, BgarefreshLayout.BgarefreshLayoutDelegate, Component.TouchEventListener {
    private String action = "com.yanzhenjie.andserver.hos";
    private MyCommonEventSubscriber myCommonEventSubscriber;
    private Intent mService;
    private Text mDesc;
    private Button mStop, mBrowser;
    private FloatingActionButton mStart;
    private String host;
    private static String path;

    private AnimatorValue animatorValue;
    private ListContainer fileLists;
    private BgarefreshLayout freshlayout;
    private Image more;
    private Text deleteAll;
    private DirectionalLayout layout_empty;
    private String substring;
    private String copyPath;
    private File copyFile;

    public String getPath() {
        return path;
    }

    public static void setPath(String p) {
        path = p;
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        EventBus.getDefault().register(this);
        getAuth();
        initView();
        freshlayout.setDelegate(MainAbilitySlice.this);

        freshlayout.setIsShowLoadingMoreView(true);
        freshlayout.setPullDownRefreshEnable(true);
        BgaStickinessRefreshViewHolder stickinessRefreshViewHolder = new BgaStickinessRefreshViewHolder(this,
                true);

        stickinessRefreshViewHolder.setPullDownRefreshText("Company Calling..");
        stickinessRefreshViewHolder.setLoadingMoreText("Loading Pull..");
        stickinessRefreshViewHolder.setUltimateColor(ResourceTable.Color_util__color);
        stickinessRefreshViewHolder.setLoadMoreBackgroundColorRes(ResourceTable.Color_load_more);
        stickinessRefreshViewHolder.setRefreshViewBackgroundColorRes(ResourceTable.Color_refresh_color);
        stickinessRefreshViewHolder.setOriginalImage(ResourceTable.Media_icon);
        stickinessRefreshViewHolder.setLoaderTextColor(ResourceTable.Color_text_color);
        stickinessRefreshViewHolder.setPullUpDilogueVisible(false);
        stickinessRefreshViewHolder.setLoaderTextSize(50);
        stickinessRefreshViewHolder.setProgressSize(90);
        freshlayout.setRefreshViewHolder(stickinessRefreshViewHolder);

//        path = this.getAbilityPackageContext().getExternalCacheDir().getAbsolutePath();
        setPath(this.getAbilityPackageContext().getExternalCacheDir().getAbsolutePath());
        FileUtils.mkDir(path.substring(0, path.length() - 5) + "abc");
        onRegisterCommonEventSubscriber();
        initlist();
    }

    private void initlist() {

        System.out.println("列表" + FileUtils.getFileList(path));
        List<fileItemModel> arrayList = new ArrayList<>();
        List<File> fileList = FileUtils.getSortFileList(path);
        System.out.println("数量====" + fileList.size());
        if (fileList.size() == 0) {
            layout_empty.setVisibility(Component.VISIBLE);
            freshlayout.setVisibility(Component.HIDE);
        } else {
            layout_empty.setVisibility(Component.HIDE);
            freshlayout.setVisibility(Component.VISIBLE);
        }

        for (int i = 0; i < fileList.size(); i++) {
            String name = fileList.get(i).getName();
            if (name.contains(".")) {
                substring = name.substring(name.indexOf("."));
            } else {
                substring = "";
            }
            System.out.println("后缀====" + substring);
            arrayList.add(new fileItemModel(fileList.get(i).getName(), "fileList.get(i).get", fileList.get(i).getPath(), fileList.get(i).length(), substring));
        }
        ListProvider listProvider = new ListProvider(arrayList, getContext());
        fileLists.setItemProvider(listProvider);
        fileLists.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
            }
        });
    }

    private void getAuth() {
        String[] per = {"ohos.permission.READ_USER_STORAGE", "ohos.permission.WRITE_MEDIA",
                "ohos.permission.READ_MEDIA", "ohos.permission.WRITE_USER_STORAGE"};
        requestPermissionsFromUser(per, 0);
    }


    /**
     * s
     * 初始化 view
     */
    private void initView() {

        mStart = (FloatingActionButton) findComponentById(ResourceTable.Id_fab);
        fileLists = (ListContainer) findComponentById(ResourceTable.Id_filelist);
        Image location = (Image) findComponentById(ResourceTable.Id_location);
        freshlayout = (BgarefreshLayout) findComponentById(ResourceTable.Id_freshLayout);
        more = (Image) findComponentById(ResourceTable.Id_more);
        deleteAll = (Text) findComponentById(ResourceTable.Id_deleteall);
        layout_empty = (DirectionalLayout) findComponentById(ResourceTable.Id_layout_empty);
        //   mStop = (Button) findComponentById(ResourceTable.Id_stop_server);
        // mBrowser = (Button) findComponentById(ResourceTable.Id_open_browser);
        // mDesc = (Text) findComponentById(ResourceTable.Id_server_desc);
        mStart.setClickedListener(this);
        location.setClickedListener(this);
        more.setClickedListener(this);
        deleteAll.setClickedListener(this);
        //  mStop.setClickedListener(this);
        //  mBrowser.setClickedListener(this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        initlist();
    }

    private boolean isClick = true;

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_fab:

                isfst = false;
                buttunAnimal();

//                FileUtils.getFileList(path.substring(0,path.length()-5)+"file");


                break;
            case ResourceTable.Id_location:
                //  present(new ListAbilitySlice(), new Intent());
                Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withAction(IntentConstants.ACTION_HIDISK_CHOOSE)
                        .build();
                intent.setOperation(operation);
                startAbilityForResult(intent, 00);
                break;
            case ResourceTable.Id_more:
//                if (isClick) {
//                    deleteAll.setVisibility(Component.VISIBLE);
//                    isClick = false;
//                } else {
//                    deleteAll.setVisibility(Component.HIDE);
//                    isClick = true;
//                }
                new XPopup.Builder(getContext())
                        .isDestroyOnDismiss(true) // 对于只使用一次的弹窗，推荐设置这个
                        .atView(component)
                        .hasShadowBg(false) // 去掉半透明背景
                        .asCustom(new CustomAttachPopup2(getContext())).show();

                break;
            case ResourceTable.Id_deleteall:

                break;

        }
    }


    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (resultData != null) {

            if (null != resultData.getParams()) {
                IntentParams parms = resultData.getParams();
                ArrayList<String> pathlist = new ArrayList<>();
                String uri1 = null;
                ArrayList<String> urilist = new ArrayList<>();
                ArrayList<File> filelist = new ArrayList<>();

                for (String key : parms.keySet()) {
                    if (parms.getParam(key) != null) {
                        pathlist = (ArrayList<String>) parms.getParam(key);
                    }

                    System.out.println("判断为空===" + pathlist);
                }
                for (int i = 0; i < pathlist.size(); i++) {
                    String path = String.valueOf(pathlist.get(i));
//                   String uri =path.substring(1, path.length() - 1);
                    uri1 = path.replace("content:", "dataability:/");
                    urilist.add(uri1);
                    copyPath = FileUtils.uriTopath(Uri.parse(uri1), MainAbilitySlice.this);

                    copyFile = new File(copyPath);
                    filelist.add(copyFile);
                }
                DataAbilityHelper dataAbilityHelper = DataAbilityHelper.creator(getContext());
                for (int i = 0; i < urilist.size(); i++) {
                    try {
                        InputStream inputStream = dataAbilityHelper.obtainInputStream(Uri.parse(urilist.get(i)));
                        FileUtils.copySdcardFile(inputStream, path + "/" + filelist.get(i).getName());
                        new ToastDialog(getContext()).setText("上传成功，请刷新网页端").show();
                    } catch (DataAbilityRemoteException e) {
                        e.fillInStackTrace();
                    } catch (FileNotFoundException e) {
                        e.fillInStackTrace();
                    }
                }
                EventBus.getDefault().post(new MessageEvent());


            }
        }
    }

    boolean isfst = true;

    private void buttunAnimal() {
        animatorValue = new AnimatorValue();
        animatorValue.setDuration(200);
        animatorValue.setDelay(10);
        animatorValue.setLoopedCount(0);
        animatorValue.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float value) {
                mStart.setHeight((int) (180 * (value)));
            }
        });
        animatorValue.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {
                Operation operation = new Intent.OperationBuilder()
                        .withBundleName(getBundleName())
                        .withAbilityName("com.yanzhenjie.andserver.ServiceAbility")
                        .build();
                mService = new Intent();
                mService.setOperation(operation);
                startAbility(mService);
            }

            @Override
            public void onStop(Animator animator) {

            }

            @Override
            public void onCancel(Animator animator) {

            }

            @Override
            public void onEnd(Animator animator) {
                if (isfst == false) {
                    dialogMain();
                    isfst = true;
                }

            }

            @Override
            public void onPause(Animator animator) {

            }

            @Override
            public void onResume(Animator animator) {

            }
        });
        animatorValue.start();


    }

    private void dialogMain() {

        //BottomDialog.showBottomDialog(this, host);
        new XPopup.Builder(getContext())
                // 如果不加这个，评论弹窗会移动到软键盘上面
                .borderRadius(20)
                .asCustom(new ZhihuCommentPopup(getContext(), host))
                .show();

    }

    /**
     * 订阅无序的公共事件
     */
    private void onRegisterCommonEventSubscriber() {
        MatchingSkills matchingSkills = new MatchingSkills();
        matchingSkills.addEvent(action); // 自定义事件
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
        myCommonEventSubscriber = new MyCommonEventSubscriber(subscribeInfo, this);
        try {
            CommonEventManager.subscribeCommonEvent(myCommonEventSubscriber);
        } catch (RemoteException e) {
            e.fillInStackTrace();
        }
    }

    /**
     * 开启服务
     *
     * @param ip
     */
    public void onStartServer(String ip) {
        this.host = "http://" + ip + ":8080/";

    }

    /**
     * 关闭服务
     */
    public void onStopServer() {
        mDesc.setText("服务已停止");
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onBgarefreshLayoutBeginRefreshing(BgarefreshLayout refreshLayout) {
        initlist();
    }

    @Override
    public boolean onBgarefreshLayoutBeginLoadingMore(BgarefreshLayout refreshLayout) {
        return false;
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        if (touchEvent.getAction() == TouchEvent.PRIMARY_POINT_DOWN) {
            deleteAll.setVisibility(Component.HIDE);
        }

        return false;
    }
}
